package com.dora.mega.data.transfer.fecade.util;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * excel工具
 *
 * @author Clarence
 * @date 2024/04/06
 */
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param response 响应
     * @param data     数据对象
     * @param clazz    Excel对象
     * @throws IOException ioexception
     */
    public static <T,U> void exportExcel(HttpServletResponse response, String sheetName, Class<T> clazz, List<U> data) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet("sheet1").doWrite(data);
    }


    /**
     * 设置导出标题
     *
     * @param response  响应
     * @param sheetName 表名字
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    public static void setExportHeader(HttpServletResponse response,String sheetName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFilename = URLEncoder.encode(sheetName+".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedFilename + "\"");
    }
}
